import db from '../../xp/db';
import * as util from '../../../util';

const userColumn = 'id,username,name,userType,createTime';
const userColumns = userColumn.split(',');
export function fetch(query, op, pageOpt) {
    return db.get('sys_institutions').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
    }).fetchPage({
        pageSize: pageOpt.pageSize,
        page: pageOpt.page,
        withRelated: [
            'pInstitution',
            {
                adminUser: qb => {
                    qb.columns(userColumns);
                }
            }
        ]
    });
}
export function find(query, op) {
    return db.get('sys_institutions').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('displayOrder');
    }).list({
        withRelated: [
            'pInstitution',
            {
                adminUser: qb => {
                    qb.columns(userColumns);
                }
            }
        ]
    });
}
export function findNoWithRelated(query, op) {
    return db.get('sys_institutions').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('displayOrder');
    }).list();
}
export function add(data, user) {
    return db.exec(model => model('sys_institutions').forge().save(data, {method: 'insert'})
        .then(() => model('sys_users').forge().save(user, {method: 'insert'})));
}

export function edit(data, user) {
    return db.exec(model => model('sys_institutions').forge().save(data, {method: 'update', require: false})
        .then(() => {
            if (user) {
                return model('sys_users').forge().save(user, {method: 'update', require: false});
            }
            return {data, user};
        }));
}
export function del(id) {
    return db.exec(model => model('sys_users').where({institutionId: id, userType: 3}).drop()
        .then(() => model('xp_activity').forge({id}).drop()));
}
